package com.dlyk.controller;

import com.alibaba.excel.EasyExcel;
import com.dlyk.bean.TCustomer;
import com.dlyk.constant.Constants;
import com.dlyk.result.CustomerExcel;
import com.dlyk.result.R;
import com.dlyk.service.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 客户管理
 */
@RestController
@Slf4j
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * 客户管理分页查询
     * @param current
     * @return
     */
    @GetMapping("/api/customers")
    public R customerList(@RequestParam Integer current){
        if (current==null){
            current=1;
        }
        PageInfo<TCustomer> pageInfo =customerService.customerPage(current);
        return R.OK(pageInfo);
    }

    /**
     * 批量导入数据到Excel
     * @return
     */
    @GetMapping("/api/importExcel")
    public void batchImportExcel(HttpServletResponse response, @RequestParam(value = "ids",required = false) String ids) throws IOException {
        response.setContentType("application/octet-stream");  // 设置内容类型
        response.setCharacterEncoding("utf-8");  // 设置字符编码

        // System.currentTimeMillis() 时间戳
        // 防止中文乱码
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(Constants.EXCEL_FILE_NAME+System.currentTimeMillis(), StandardCharsets.UTF_8) +".xlsx");  // 设置相应头
        // 将id存入list集合
        List<String> idList= StringUtils.hasText(ids) ? Arrays.asList(ids.split(",")) : new ArrayList<>();

        // 查询数据库的数据，把数据写入到Excel，然后把Excel以IO流的方式输出到前端浏览器
        List<CustomerExcel> list=customerService.getCustomerByExcel(idList);
        EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                .sheet()
                .doWrite(list);
    }
}
